package com.app.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.PhoneUtil;
import com.app.common.SystemConstant;
import com.app.enums.StatusCodeEnum;
import com.app.util.COSClientUtil;
import com.app.util.FileTypeCheckerUtil;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Controller
@RestController
@RequestMapping("/file")
@Api(tags = "图片上传删除接口")
public class UploadController {

    /**
     * 上传文件
     */
    @ApiOperation("上传图片到本地")
    @PostMapping("/upload")
    public Result<?> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {

        if (!FileTypeCheckerUtil.isAllowedFileType(file)){
            return Result.error("文件类型错误!");
        }
        File filePath;
        if (!file.isEmpty()) {
            //上传文件路径
            String path = "";
            path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            int lastIndexOf = fileName.lastIndexOf(".");
            String date = IdUtil.fastUUID();
            //获取文件的后缀名 .jpg
            String suffix = fileName.substring(lastIndexOf);
            filePath = new File(path + date + suffix);
            //如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
            return Result.success("/file/" + date + suffix);
        } else {
            return Result.error("上传失败");
        }
    }


    @ApiOperation("上传图片到腾讯云对象存储")
    @PostMapping("/uploadToCOS")
    public Result uploadToCOS(HttpServletRequest request) throws IOException {
        // 获取文件
        List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("file");
//        for (MultipartFile f:file) {
////            //判断文件上传格式
//            if (!FileTypeCheckerUtil.isAllowedFileType(f)){
//                return Result.error("文件类型错误!");
//            }
//        }
        File[] filePath = new File[file.size()];
        String[] url = new String[file.size()];

        String webUrl = "";
        if (!file.isEmpty()) {
            //上传文件路径
            String path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            for (int i1 = 0; i1 < file.size(); i1++) {
                String fileName = file.get(i1).getOriginalFilename();
                assert fileName != null;
                int lastIndexOf = fileName.lastIndexOf(".");
                long time = System.currentTimeMillis();
                String date = "COS_" + time;
                //获取文件的后缀名 .jpg
                String suffix = fileName.substring(lastIndexOf);
                File filePath1 = new File(path + File.separator + date + suffix);
                //如果文件目录不存在，创建目录
                if (!filePath1.getParentFile().exists()) {
                    boolean mkdirs = filePath1.getParentFile().mkdirs();
                }
                file.get(i1).transferTo(filePath1);
                filePath[i1] = filePath1;
            }
        } else {
            return Result.error("上传失败");
        }
        for (int i = 0; i < filePath.length; i++) {
            //获取COSClient对象
            COSClient cosClient = COSClientUtil.getCosClient();
            // 设置存储桶名称和文件路径
            String bucketName = SystemConstant.bucketName;
            String key = "file/" + filePath[i].getName();
            File localFile = new File(filePath[i].getPath());
            try {
                // 上传文件到存储桶
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
                // 设置存储桶权限
                putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
                cosClient.putObject(putObjectRequest);
                File file1 = new File(filePath[i].getPath());
                String fileUrl = SystemConstant.OBJECT_STORAGE_URL + file1.getName();
                webUrl = file1.getName();
                System.out.println("文件上传存储桶成功");
                if (file1.delete()) {
                    System.out.println(file1.getName() + " 图片已被删除！");
                } else {
                    System.out.println("删除图片操作失败！");
                }
                url[i] = fileUrl;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭存储桶客户端
                cosClient.shutdown();
            }
        }
        return Result.success(webUrl);
    }


    //删除对象
    @ApiOperation(value = "删除图片")
    @GetMapping("/deleteObject")
    public Result<Object> deleteObject(String filename) {
        //获取COSClient对象
        COSClient cosClient = COSClientUtil.getCosClient();
        // Bucket 的命名格式为 BucketName-APPID ，此处填写的存储桶名称必须为此格式
        String bucketName = SystemConstant.bucketName;
        // 指定被删除的文件在 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示删除位于 folder 路径下的文件 picture.jpg
        String key = "/uploads/FFuFQ6QV.png";
        cosClient.deleteObject(bucketName, key);
        return Result.success("删除成功");
    }

    /**
     * 将URL转换为本地文件路径
     * @param fileUrl 文件URL(如 https://域名/file/合同.pdf)
     * @param basePath 本地基础路径(如 /var/www/html)
     * @return 本地文件对象
     */
    public static File urlToLocalFile(String fileUrl, String basePath) throws URISyntaxException {
        URI uri = new URI(fileUrl);
        String path = uri.getPath(); // 获取路径部分，如 /file/合同.pdf

        // 组合基础路径和相对路径
        return new File(basePath, path);
    }
}
